//
//  DBLocationTool.swift
//  DBCA
//
//  Created by mugua on 2024/7/7.
//

import Foundation

struct DBLocationModel {
    
    public var country_code: String?
    public var country_name: String?
    public var admin_area: String?
    public var locality: String?
    public var sub_admin_area: String?
    public var feature_name: String?
    public var latitude: String?
    public var longitude: String?
}

typealias locationBlock = ((_ model: DBLocationModel) -> ())
typealias finishBlock = ((_ isFinish: Bool) -> ())

class DBLocationTool: NSObject, CLLocationManagerDelegate {
    
    var currentLocationBlock: locationBlock?
    var currentFinishBlock: finishBlock?
    
    private lazy var locationManager: CLLocationManager = {
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        return locationManager
    }()
    
    
    
    func requestStatus(block: finishBlock?){
        currentFinishBlock = block
        
        if #available(iOS 14.0, *) {
            if locationManager.authorizationStatus == .notDetermined {
                locationManager.requestWhenInUseAuthorization()
            } else {
                
                if locationManager.authorizationStatus == .denied {
                    DBToast.show(text: "禁止了定位 显示弹框 待实现")
                }
            }
        } else {
            if CLLocationManager.authorizationStatus() == .notDetermined {
                locationManager.requestWhenInUseAuthorization()
            } else{
                if CLLocationManager.authorizationStatus() == .denied {
                    DBToast.show(text: "禁止了定位 显示弹框 待实现")
                }
            }
        }
    }
    
    
    func getLocation(block: @escaping locationBlock) {
        currentLocationBlock = block
        if self.isAllow() {
            locationManager.startUpdatingLocation()
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .denied:
            showAlert()
        case .authorizedWhenInUse, .authorizedAlways:
            guard let currentFinishBlock = currentFinishBlock else { return }
            currentFinishBlock(true)
        default:
            break
        }
    }
    
    @available(iOS 14.0, *)
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        switch manager.authorizationStatus {
        case .denied:
            showAlert()
        case .authorizedWhenInUse, .authorizedAlways:
            guard let currentFinishBlock = currentFinishBlock else { return }
            currentFinishBlock(true)
        default:
            break
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locationManager.stopUpdatingLocation()
        guard let currentLocation = locations.last else { return }
        let geoCoder = CLGeocoder()
        
        geoCoder.reverseGeocodeLocation(currentLocation) { [weak self] placemarks, error in
            guard let self = self else { return }
            guard let placemarks = placemarks, placemarks.count > 0, let placemark = placemarks.first else { return }
            
            var model = DBLocationModel()
            model.country_code = placemark.isoCountryCode
            model.country_name = placemark.country
            model.admin_area = placemark.administrativeArea
            model.locality = placemark.locality
            model.sub_admin_area = placemark.subLocality
            model.feature_name = placemark.name
            model.latitude = String(format: "%lf", currentLocation.coordinate.latitude)
            model.longitude = String(format: "%lf", currentLocation.coordinate.longitude)
            
            UserDefaults.standard.setValue(model.latitude, forKey: DBLatitude)
            UserDefaults.standard.setValue(model.longitude, forKey: DBLongitude)
            UserDefaults.standard.synchronize()
            
            guard let currentLocationBlock = self.currentLocationBlock else { return }
            currentLocationBlock(model)
            
        }
    }
    
    func showAlert() {
        
    }
    
    func isAllow() -> Bool {
        if #available(iOS 14.0, *) {
            return locationManager.authorizationStatus == .authorizedWhenInUse
        } else {
            return CLLocationManager.authorizationStatus() == .authorizedWhenInUse
        }
    }
}
